pub mod thread_stack;

use core::mem;
use crate::memory::pointer::SizePointer;

/// Stack的抽象定义
pub trait Stack {
    /// 存入栈帧到栈
    fn push(&mut self, sf: StackFrame) -> StackResult<()>;
    /// 从栈中pop一个元素
    fn pop<T>(&mut self) -> StackResult<T>;
}

/// 统一返回Result类型
type StackResult<T> = Result<T, StackErrors>;

/// 栈错误信息
pub enum StackErrors {
    StackOverflow,
    NonexistentFrame,
}

/// 栈帧对象
#[derive(Debug)]
pub struct StackFrame {
    is_address: bool,
    value: usize,
    size: usize,
}

impl From<SizePointer> for StackFrame {
    fn from(p: SizePointer) -> Self {
        Self {
            is_address: true,
            value: p.address(),
            size: p.type_size(),
        }
    }
}

impl StackFrame {
    pub fn new_address(start: usize, size: usize) -> Self {
        StackFrame { is_address: true, value: start, size }
    }

    pub fn new_immediate(value:usize) -> Self {
        let size = mem::size_of::<usize>();
        StackFrame { is_address: false, value, size }
    }

    pub fn to_pointer(&self) -> SizePointer {
        unsafe { SizePointer::new_unknown(self.value, self.size) }
    }
}

